import store from '@/store'
import axios from 'axios'
import {
  Message
} from 'element-ui'
import { getTime } from '@/utils/auth'
import router from '@/router'

const checkTime = () => {
  const now = new Date()
  const old = getTime()
  const duration = 60 * 60 * 12
  return now - old > duration
}

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  const token = store.getters.token
  if (token) {
    if (checkTime()) {
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('token2 已超时'))
    } else {
      config.headers.Authorization = token
    }
  }
  return config
}, err => {
  Message.error(err.message)
  return Promise.reject(err)
})

// response interceptor
service.interceptors.response.use(
  res => {
    // console.log(res)
    const {
      success,
      message,
      data
    } = res.data
    if (success) {
      return data
    } else {
      Message.error(message)
      return Promise.reject(message)
    }
  },
  err => {
    if (err.response && err.response.data && err.response.data.code === 10002) {
      store.dispatch('user/logout')
      router.push('/login')
      Message.message(err.message)
    } else {
      Message.error(err.message)
    }
    return Promise.reject(err)
  }
)

export default service
